//
//  ESMainViewController.m
//  EasyStyle
//
//  Created by FK on 15/12/11.
//  Copyright © 2015年 FK. All rights reserved.
//

#import "ESMainViewController.h"
#import "MMDrawerBarButtonItem.h"
#import "UIViewController+MMDrawerController.h"
#import "MJRefresh.h"

#import "ESMainNetTaskManager.h"

#import "ESMainCardDAO.h"

#import "ESCardHoroscopeView.h"
#import "ESWeatherView.h"
#import "ESCardWeatherDetailView.h"
#import "ESCardNewsWordsView.h"
#import "ESCardLastedJokesView.h"

#import "ESWeatherNetResult.h"
#import "ESTrainStationNetResult.h"


#import "ESNewsWordsSearchViewController.h"
#import "ESJokesSearchViewController.h"
#import "ESHoroscopeSearchViewController.h"
#import "ESWeatherCityListViewController.h"



static const CGFloat kESMainViewScrollViewMargin = 4.0f; // 两边边缘距离
static const CGFloat kESMainViewScrollViewinterval = 9.0f; // view间距
static const NSTimeInterval kESMainViewScrollViewCardAnimationDuration = 0.2; // card位置变化动画持续时间
static NSString * const kESWeiXinSelectedVCLastedUpdateTimeKey = @"ESMainVC_MJMJRefresh_LastedUpdateTime";

@interface ESMainViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong)UIScrollView           *mainScrollView;

@property (nonatomic, strong)ESWeatherView          *cardWearther;
@property (nonatomic, strong)ESCardWeatherDetailView *cardWeatherDeteil;
@property (nonatomic, strong)NSDictionary           *weatherDataDict;


@property (nonatomic, strong)ESCardHoroscopeView    *cardHoroscope;
@property (nonatomic, strong)NSDictionary           *horoscopeDataDict;

@property (nonatomic, strong)ESCardNewsWordsView    *cardNewsWords;
@property (nonatomic, strong)NSArray                *newsWordsDataList;

@property (nonatomic, strong)ESCardLastedJokesView  *cardLastedJokes;
@property (nonatomic, strong)NSArray                *lastedJokesDataList;

//@property (nonatomic, strong)UIView                 *trainStationView;

@end

BOOL isShowWeatherDetail = NO;

BOOL isShowNetErrorAlert = NO;

@implementation ESMainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateWeather:) name:LocationSupportUpdateWeatherNotification object:nil];


    /// 加载旧数据
    [self loadData];
    
    /// 加载卡片
    [self loadCard];
    
    [self setupRootView:self.view.frame];
    
    [self setupRefresh];
    
    [self setupScrollViewContent:self.mainScrollView.frame];
    
    // 请求新数据
    [self refreshData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark -- 辅助函数
// 根据上次刷新时间判断现在是否自动刷新   大于2小时则自动刷新
- (BOOL)canUpdateNewsList
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader new];
    header.lastUpdatedTimeKey = kESWeiXinSelectedVCLastedUpdateTimeKey;
    NSDate *lastUpdateTime = header.lastUpdatedTime;
    
    if (lastUpdateTime == nil) {
        return NO;
    }
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
    NSDateComponents *maxDateComponent = [[NSDateComponents alloc] init];
    [maxDateComponent setHour:2];
    NSDate *maxDepartDate = [calendar dateByAddingComponents:maxDateComponent toDate:lastUpdateTime options:0];
    
    NSDate *now = [NSDate date];
    if ([now compare:maxDepartDate] == NSOrderedAscending || [now compare:maxDepartDate] == NSOrderedSame) {
        return NO;
    }
    
    return YES;
}

- (void)showErrorViewWithErrorMsg:(NSString *)errorMsg
{
    if (!isShowNetErrorAlert) {
        isShowNetErrorAlert = YES;
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"遗憾" message:errorMsg delegate:self cancelButtonTitle:@"明白" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

#pragma mark -- load
- (void)loadData
{
    ESMainCardDAO *dao = [ESMainCardDAO shareInstance];
    
    _weatherDataDict = [dao queryWeatherData];
    
    _horoscopeDataDict = [dao queryHoroscopeDataWithType:ESCardHoroscopeType_today];
    
    _newsWordsDataList = [dao queryNewsWordsData];
    
    _lastedJokesDataList = [dao queryLastedJokesData];
}

- (void)loadCard
{
    /// 天气  以及 天气详情
    if (!_cardWearther) {
        _cardWearther =  [ESWeatherView loadViewFromSameXibName];
        WS(weakSelf);
        _cardWearther.blockShowWeatherDetail = ^() {
            isShowWeatherDetail?(isShowWeatherDetail = NO):(isShowWeatherDetail = YES);
            [weakSelf setupScrollViewContent:weakSelf.mainScrollView.frame];
        };
        
    }
    if (!_cardWeatherDeteil) {
        _cardWeatherDeteil = [ESCardWeatherDetailView loadViewFromSameXibName];
        WS(weakSelf);
        _cardWeatherDeteil.blockCloseWeatherDetail = ^() {
            isShowWeatherDetail?(isShowWeatherDetail = NO):(isShowWeatherDetail = YES);
            [weakSelf setupScrollViewContent:weakSelf.mainScrollView.frame];
        };
        _cardWeatherDeteil.blockSelectCity = ^() {
            weakSelf.hidesBottomBarWhenPushed = YES;
            ESWeatherCityListViewController *citySelectVC = [ESWeatherCityListViewController new];
            [weakSelf.navigationController pushViewController:citySelectVC animated:YES];
            weakSelf.hidesBottomBarWhenPushed = NO;
        };
    }
    if (_weatherDataDict) {
        [_cardWearther loadCardWithData:_weatherDataDict];
        [_cardWeatherDeteil loadCardWithData:_weatherDataDict];
    }
    
    /// 星座运势
    if (!_cardHoroscope) {
        _cardHoroscope = [ESCardHoroscopeView loadViewFromSameXibName];
        WS(weakSelf);
        _cardHoroscope.blockHoroscopeDetail = ^() {
            weakSelf.hidesBottomBarWhenPushed = YES;
            
            UIStoryboard *mainSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            
            
            ESHoroscopeSearchViewController *horoscopeDetailSearchVC = [mainSB instantiateViewControllerWithIdentifier:@"HoroscopeSearchViewController"];
            
//            ESHoroscopeSearchViewController *horoscopeDetailSearchVC = [ESHoroscopeSearchViewController new];
            [weakSelf.navigationController pushViewController:horoscopeDetailSearchVC animated:YES];
            
            
            weakSelf.hidesBottomBarWhenPushed = NO;
        };
    }
    if (_horoscopeDataDict) {
        [_cardHoroscope loadCardWithData:_horoscopeDataDict];
    }
    
    /// 新闻热词
    if (!_cardNewsWords) {
        _cardNewsWords = [ESCardNewsWordsView loadViewFromSameXibName];
        
        WS(weakSelf);
        _cardNewsWords.newsWordClickBlock = ^(NSString *newsWord) {
            weakSelf.hidesBottomBarWhenPushed = YES;
            ESNewsWordsSearchViewController *newsWordsSearchVC = [ESNewsWordsSearchViewController new];
            newsWordsSearchVC.newsWord = newsWord;
            [weakSelf.navigationController pushViewController:newsWordsSearchVC animated:YES];
            weakSelf.hidesBottomBarWhenPushed = NO;
        };
    }
    if (_newsWordsDataList) {
        [_cardNewsWords loadCardWithData:_newsWordsDataList];
    }
    
    /// 笑话
    if (!_cardLastedJokes) {
        _cardLastedJokes = [ESCardLastedJokesView loadViewFromSameXibName];
        
        WS(weakSelf);
        _cardLastedJokes.buttonClick = ^(CGFloat newHeight) {
            [weakSelf setupScrollViewContent:weakSelf.mainScrollView.frame];
        };
        
        _cardLastedJokes.blockGetMoreJokesClick = ^() {
            weakSelf.hidesBottomBarWhenPushed = YES;
            ESJokesSearchViewController *moreJokesVC = [ESJokesSearchViewController new];
            [weakSelf.navigationController pushViewController:moreJokesVC animated:YES];
            weakSelf.hidesBottomBarWhenPushed = NO;
            
        };
    }
    if (_lastedJokesDataList) {
        [_cardLastedJokes loadCardWithData:_lastedJokesDataList];
    }
    
//    
//    /// 火车到站/车次查询
//    _trainStationView = [[UIView alloc]init];
//    _trainStationView.backgroundColor = [UIColor redColor];
//    _trainStationView.alpha = 0.8;
}


#pragma mark -- 布局相关
- (void)setupRootView:(CGRect)parentFrame
{
    self.view.backgroundColor= [UIColor colorWithHex:@"e7e3d8"];
    
    NSInteger startY = 0;
    NSInteger endY   = 0;

    self.navigationController.navigationBarHidden = YES;

    [self addCustomNavigationBarWithStyle:DefaultStyle customColor:[UIColor clearColor]];
    UIImageView *navigatonBarImage = [[UIImageView alloc]init];
    navigatonBarImage.frame = CGRectMake(0, 0, self.sgCustomNavigationBar.width, self.sgCustomNavigationBar.height);
    navigatonBarImage.image = [UIImage imageNamed:@"homeNavigationBarBG@2x"];
    [self.sgCustomNavigationBar insertSubview:navigatonBarImage atIndex:0];
    
    [self.sgCustomNavigationBar setTitle:@"来点资讯"];
    self.sgCustomNavigationBar.titleLabel.textColor = [UIColor whiteColor];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 20, 50, 40)];
    leftButton.backgroundColor = [UIColor clearColor];
    [leftButton setImage:[UIImage imageNamed:@"hamb-menu"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"hamb-menu"] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.sgCustomNavigationBar addSubview:leftButton];
    
    startY += self.navigationController.navigationBar.height + StatusBarHeight;
    
    endY += self.tabBarController.tabBar.frame.size.height;
    
    ///初始化mainScrollView
    self.mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, startY, self.view.width, self.view.height-startY - endY)];
    self.mainScrollView.clipsToBounds = NO;
    self.mainScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mainScrollView.backgroundColor = [UIColor colorWithHex:@"e7e3d8"];
    self.mainScrollView.alpha = 1;
    self.mainScrollView.bounces = YES;
    self.mainScrollView.showsHorizontalScrollIndicator = NO;
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    self.mainScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.mainScrollView.delegate = self;
    [self.view addSubview:self.mainScrollView];
    
    [self.view bringSubviewToFront:self.sgCustomNavigationBar];
}

- (void)setupScrollViewContent:(CGRect)parentFrame
{
    CGSize parentSize = parentFrame.size;
    
    NSInteger startX = kESMainViewScrollViewMargin;
    NSInteger endX   = parentSize.width - kESMainViewScrollViewMargin;
    NSInteger startY = 0;
    
    
    /// 天气预报
    if (!isShowWeatherDetail) {
        _cardWeatherDeteil.alpha = 0;
        startY += kESMainViewScrollViewinterval;
        [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
            _cardWearther.alpha = 1;
            [_cardWearther setFrame:CGRectMake(startX, startY, endX - startX, _cardWearther.height)];
            [self.mainScrollView addSubview:_cardWearther];
        }];
        startY += _cardWearther.height;
    } else {
        _cardWearther.alpha = 0;
        startY += kESMainViewScrollViewinterval;
        [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
            _cardWeatherDeteil.alpha = 1;
            [_cardWeatherDeteil setFrame:CGRectMake(0, 0, parentSize.width, _cardWeatherDeteil.height)];
            [self.mainScrollView addSubview:_cardWeatherDeteil];
        }];
        startY += _cardWeatherDeteil.height;
    }
    
    /// 星座运势
    startY += kESMainViewScrollViewinterval;
    [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
        [_cardHoroscope setFrame:CGRectMake(startX, startY, endX - startX, _cardHoroscope.height)];
        [self.mainScrollView addSubview:_cardHoroscope];
    }];
    startY += _cardHoroscope.height;
    
    /// 新闻热词
    startY += kESMainViewScrollViewinterval;
    [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
        [_cardNewsWords setFrame:CGRectMake(startX, startY, endX - startX, _cardNewsWords.height)];
        [self.mainScrollView addSubview:_cardNewsWords];
    }];
    startY += _cardNewsWords.height;
    
    /// 笑话
    startY += kESMainViewScrollViewinterval;
    [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
        [_cardLastedJokes setFrame:CGRectMake(startX, startY, endX - startX, _cardLastedJokes.height)];
        [self.mainScrollView addSubview:_cardLastedJokes];
    }];
    startY += _cardLastedJokes.height;
    
//    /// 火车到站/车次查询
//    startY += kESMainViewScrollViewinterval;
//    [UIView animateWithDuration:kESMainViewScrollViewCardAnimationDuration animations:^{
//        [_trainStationView setFrame:CGRectMake(startX, startY, endX - startX, 100)];
//        [self.mainScrollView addSubview:_trainStationView];
//        UIButton *btnStation = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 60)];
//        btnStation.centerY = _trainStationView.height / 2;
//        btnStation.centerX = _trainStationView.width / 2;
//        [btnStation setTitle:@"这是火车到站/车次查询" forState:UIControlStateNormal];
//        [btnStation setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [_trainStationView addSubview:btnStation];
//    }];
//    
//    startY += _trainStationView.height;
    
    // 设置内容大小
    self.mainScrollView.contentSize = CGSizeMake(self.view.width, startY + 20);
}

- (void)setupRefresh
{
    WS(weakSelf);
    //下拉刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf startNetWorkAtlanuch];
    }];
    [header setTitle:@"" forState:MJRefreshStateIdle];
    [header setTitle:@"松手 给你好看" forState:MJRefreshStatePulling];
    [header setTitle:@"稍等!只为给你更好的" forState:MJRefreshStateRefreshing];
    [header setTitle:@"别拉了 好看的都在这了" forState:MJRefreshStateNoMoreData];
    _mainScrollView.mj_header = header;
}

- (void)resetScrollViewContentSize
{
    // 设置内容大小
    self.mainScrollView.contentSize = CGSizeMake(self.view.width, self.mainScrollView.contentSize.height + 20);
    
}


#pragma mark -- 数据相关
- (void)startNetWorkAtlanuch
{
    //// 做更新判断逻辑
    [self loadCardWeatherData];
    [self loadCardHoroscopeDataWithUpdate:YES];
    [self loadCardNewsWordsData];
    [self loadCardLastedJokesData];
    
    //// 后台获取所有星座的运势数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
    });
    //    [self loadCardTrainStationQueryData];
}

/// 天气
- (void)loadCardWeatherData
{
    isShowNetErrorAlert = NO;
    //    WS(weakSelf);
    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
    
    [netTask setBlockWithReturnBlock:^(id result) {
        /// 这里写刷新view逻辑
        if ([result isKindOfClass:[NSDictionary class]]) {
            //            _weatherNetResult = [ESWeatherNetResult new];
            
            //            [_weatherNetResult getDetailWeatherData:result andDataType:nil];
            _weatherDataDict = result;
            [_cardWearther loadCardWithData:_weatherDataDict];
            [_cardWeatherDeteil loadCardWithData:_weatherDataDict];
            
            // 结束刷新
            [_mainScrollView.mj_header endRefreshing];
            NSLog(@"asdadasd");
        }
        
    } WithErrorBlock:^(id errorCode) {
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
        
        [self showErrorViewWithErrorMsg:errorCode];
        
    } WithFailureBlock:^{
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
    }];
    
    [netTask loadCardWeatherData];
}

/// 星座运势
- (void)loadCardHoroscopeDataWithUpdate:(BOOL)isUpdate
{
    
    //    WS(weakSelf);
    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
    
    [netTask setBlockWithReturnBlock:^(id result) {
        /// 这里写刷新view逻辑
        if ([result isKindOfClass:[NSDictionary class]]) {
            _horoscopeDataDict = result;
            [_cardHoroscope loadCardWithData:_horoscopeDataDict];
            //            [weakSelf resetScrollViewContentSize];
            // 结束刷新
            [_mainScrollView.mj_header endRefreshing];
            
        }
    } WithErrorBlock:^(id errorCode) {
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
//        [self showErrorViewWithErrorMsg:errorCode];
        
    } WithFailureBlock:^{
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
    }];
    
    [netTask loadCardHoroscopeDataWithUpdate:isUpdate andHoroscopeType:ESCardHoroscopeType_today];
}



/// 新闻热词
- (void)loadCardNewsWordsData
{

    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
    
    [netTask setBlockWithReturnBlock:^(id result) {
        /// 这里写刷新view逻辑
        if ([result isKindOfClass:[NSArray class]]) {
            _newsWordsDataList = result;
            [_cardNewsWords loadCardWithData:_newsWordsDataList];
            NSLog(@"新闻热词 --- 数据oK");
            // 结束刷新
            [_mainScrollView.mj_header endRefreshing];
        }
    } WithErrorBlock:^(id errorCode) {
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
//        [self showErrorViewWithErrorMsg:errorCode];
    } WithFailureBlock:^{
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
    }];
    [netTask loadCardNewsWordsData];
}

/// 最新笑话
- (void)loadCardLastedJokesData
{

    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
    
    [netTask setBlockWithReturnBlock:^(id result) {
        /// 这里写刷新view逻辑
        if ([result isKindOfClass:[NSArray class]]) {
            _lastedJokesDataList = result;
            [_cardLastedJokes loadCardWithData:_lastedJokesDataList];
            NSLog(@"最新笑话 --- 刷新oK");
            // 结束刷新
            [_mainScrollView.mj_header endRefreshing];
        }
    } WithErrorBlock:^(id errorCode) {
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
    } WithFailureBlock:^{
        // 结束刷新
        [_mainScrollView.mj_header endRefreshing];
    }];
    [netTask loadCardJokesDataWithPageNum:1];
}


////// 获取所有星座数据
//- (void)updateAllHoroscopeData
//{
//    //    WS(weakSelf);
//    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
//    
//    [netTask setBlockWithReturnBlock:^(id result) {
//        /// 这里写刷新view逻辑
//        if ([result isKindOfClass:[NSDictionary class]]) {
//            _horoscopeDataDict = result;
//            [_cardHoroscope loadCardWithData:_horoscopeDataDict];
//            //            [weakSelf resetScrollViewContentSize];
//
//            
//        }
//    } WithErrorBlock:^(id errorCode) {
//
//    } WithFailureBlock:^{
//
//    }];
//    
//    [netTask loadCardHoroscopeDataWithUpdate:YES andHoroscopeType:ESCardHoroscopeType_today];
//}

///// 火车站到站查询
//- (void)loadCardTrainStationQueryData
//{
//    ESMainNetTaskManager *netTask = [ESMainNetTaskManager new];
//    
//    [netTask setBlockWithReturnBlock:^(id result) {
//        /// 这里写刷新view逻辑
//        if ([result isKindOfClass:[ESTrainStationNetResult class]]) {
//            
//            NSLog(@"火车站到站查询 --- 数据oK");
//            // 结束刷新
//            [_mainScrollView.mj_header endRefreshing];
//        }
//        
//    } WithErrorBlock:^(id errorCode) {
//        // 结束刷新
//        [_mainScrollView.mj_header endRefreshing];
//        [self showErrorViewWithErrorMsg:errorCode];
//    } WithFailureBlock:^{
//        // 结束刷新
//        [_mainScrollView.mj_header endRefreshing];
//    }];
//    
//    [netTask loadCardTrainStationQueryData];
//}


#pragma mark -- 加载卡片
//- (void)loadCardHoroscope
//{
//    ESDataController *dataController = [ESDataController shareInstance];
//    NSDate *lastUpdateTime = [dataController getHoroscopeUpdateTime];
//
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierChinese];
//    NSDateComponents *maxDateComponent = [[NSDateComponents alloc] init];
//    [maxDateComponent setDay:1];
//    NSDate *maxDepartDate = [calendar dateByAddingComponents:maxDateComponent toDate:lastUpdateTime options:0];
//
//    NSDate *today = [NSDate date];
//    if ([today compare:maxDepartDate] == NSOrderedAscending || [today compare:maxDepartDate] == NSOrderedSame) {
//        /// 不更新逻辑 （p.s:时间处理上可能有问题）
//        _cardHoroscope = [ESCardHoroscopeView loadViewFromSameXibName];
//
//    }else {
//        [self startNetWork];
//    }
//}

#pragma mark - 事件相关
- (void)refreshData
{
    if (![self canUpdateNewsList]) {
        if ((_weatherDataDict != nil && _weatherDataDict.count > 0) || (_horoscopeDataDict != nil && _horoscopeDataDict.count > 0) || (_newsWordsDataList != nil && _newsWordsDataList.count > 0) || (_lastedJokesDataList != nil && _lastedJokesDataList.count > 0)) {
           
        } else {
           
            // 马上进入刷新状态
            [_mainScrollView.mj_header beginRefreshing];
            [_mainScrollView.mj_header setLastUpdatedTimeKey:kESWeiXinSelectedVCLastedUpdateTimeKey];
        }
    } else {
        // 马上进入刷新状态
        [_mainScrollView.mj_header beginRefreshing];
        [_mainScrollView.mj_header setLastUpdatedTimeKey:kESWeiXinSelectedVCLastedUpdateTimeKey];
    }
    
   
}
-(void)leftDrawerButtonPress:(id)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}
- (void)updateWeather:(NSNotification *)aNotification
{
    if ([aNotification.name isEqualToString:LocationSupportUpdateWeatherNotification]) {
        [self loadCardWeatherData];
    }
}

@end
